package zack.gateway.core.datasource.connection;

import zack.gateway.core.datasource.Connection;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;


/**封装http的POST请求
 * @author A1793
 */
public class HTTPConnection implements Connection {

    HttpClient httpClient;
    //请求方法
    PostMethod postMethod;

    public HTTPConnection(String uri) {
        httpClient = new HttpClient();
        //配置请求路径
        postMethod = new PostMethod(uri);
        //设置请求头
        //表示客户端（当前代码中的HTTPClient）可以接受任意类型的响应数据（如 JSON、XML、文本等）
        postMethod.setRequestHeader("accept","*/*");
        //设置请求体格式
        postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        postMethod.setRequestHeader("Connection", "keep-alive");
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
    }

    @Override
    public Object execute(String methodName, String[] parameterTypes, String[] parameterNames, Object[] args) {
        String res = " ";
        try{
            //客户端执行请求
            int code = httpClient.executeMethod(postMethod);
            if(code == 200){
                res = postMethod.getResponseBodyAsString();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return res;
    }
}
